module Singly
  class Http
    class << self
      include Singly::Logger

      def base_url
        "https://api.singly.com/#{Singly.version}"
      end

      def fetch(path, options={})
        log("#{path} with #{options}")
        response = do_http(base_url, path, options)
        validate_response(response)
        parse_response(response)
      end

      def do_http(base_url, path, options)
        begin
          HTTParty.send(options.delete(:method) || :get, "#{base_url}#{path}", options)
        rescue Timeout::Error => e
          raise Singly::TimeoutError.new(timeout: options[:timeout], path: "#{base_url}#{path}")
        end
      end

      private

      def parse_response(response)
        response.parsed_response
      end

      def validate_response(response)
        raise Singly::ApiError.new(response: response.parsed_response, path: response.request.last_uri.to_s) if response.code != 200
      end
    end
  end
end